<?php

namespace App\Services;

use App\Models\AcceptRecord;
use App\Models\WxClient;
use Auth;

class AdminService
{
    const ROLE_SUPER_ADMIN = 1; // 超级管理员
    const ROLE_ADMIN = 2; // 一般后台操作员
    
    protected $_adminUser;

    public function __construct()
    {
        $this->_adminUser = Auth::user();
    }

    public function canShowAdminMenu($_user=null)
    {
        $validUser = $_user ?? $this->_adminUser;
        return $validUser->role == self::ROLE_SUPER_ADMIN;
    }

    public function updateAcceptRecord(array $_filter)
    {
//        $is_save = false;
//        // 先判断此客户是否在此项目下被认领了
//        $hasRecord = AcceptRecord::where(['project_id' => $_filter['project_id'],
//            'customers' => $_filter['customer_id']])->first();
//        if (is_null($hasRecord)) {
            // 没有被认领, 可以认领
        // 审核的时候,不去要判断该客户是否被认领掉 直接新增一条记录
        $accept_record = AcceptRecord::where(['project_id' => $_filter['project_id']
            , 'user_id' => $_filter['user_id']])
            ->first();
        if (empty($accept_record)) {
            // 新建一条记录
            $acceptRecord = new AcceptRecord();
            $acceptRecord->company_id = $_filter['company_id'];
            $acceptRecord->project_id = $_filter['project_id'];
            $acceptRecord->user_id = $_filter['user_id'];
            $acceptRecord->customers = array($_filter['customer_id']);
            $acceptRecord->save();
            $is_save = true;
        } else {
            $customer_arr = $accept_record->customers;
            if (!in_array($_filter['customer_id'], $customer_arr)) {
                array_push($customer_arr, $_filter['customer_id']);
                $accept_record->customers = $customer_arr;
                $accept_record->save();
                $is_save = true;
            } else {
                $is_save = true;
            }
        }
        return $is_save;
    }

    public static function getCompanyStatus($company_id) {
        //TODO:根据配置文件获取业务线状态
        return [
            '已看房' ,
            '已签约' ,
            '已付款' ,
            '已交房' ,
        ];
    }

    // 项目创建 随机分配一个未使用的微信号
    public function getRandWx() {
        $wx_ids = WxClient::where('project_id', '')->select('id')->get()->pluck('id')->all();
        if (count($wx_ids) != 0) {
            $index = rand(0, count($wx_ids)-1);
            return $wx_ids[$index];
        } else {
            return false;
        }
    }
}